﻿using AutoMapper;
using BackData;
using Domain;
using Infratructure;
using MediatR;
using Server.API.Application.Command.Goods;
using Server.API.DTOs;

namespace Server.API.Application.Handler.Goods
{
    public class GoodsGetHandler : IRequestHandler<GoodsGetCommand, APIPaging<GoodDTO>>
    {
        private readonly IRepository<GoodsModel> goodsway;
        private readonly IMapper mapper;

        public GoodsGetHandler(IRepository<GoodsModel> goodsway, IMapper mapper)
        {
            this.goodsway = goodsway;
            this.mapper = mapper;
        }
        /// <summary>
        /// 商品列表
        /// </summary>
        /// <param name="request">参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>商品列表</returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<APIPaging<GoodDTO>> Handle(GoodsGetCommand request, CancellationToken cancellationToken)
        {
            APIPaging<GoodDTO> res = new APIPaging<GoodDTO>();
            var query = goodsway.GetAll().Where(x => x.IsDel == false);
            if (!string.IsNullOrEmpty(request.GoodsName))
            {
                query = query.Where(x => x.GoodsName.Contains(request.GoodsName));
            }
            if (!string.IsNullOrEmpty(request.Order))
            {
                query = query.Where(x => x.Order.Contains(request.Order));
            }
            if (request.Expired != null)
            {
                query = query.Where(x => x.Expired == request.Expired);
            }
            if (!string.IsNullOrEmpty(request.Allownum))
            {
                query = query.Where(x => x.Allownum.Contains(request.Allownum));
            }
            if (!string.IsNullOrEmpty(request.Companyname))
            {
                query = query.Where(x => x.Companyname.Contains(request.Companyname));
            }
            res.Message = $"成功获取商品信息";
            res.Num = StateCode.OK;
            res.Totalcount = query.Count();
            var result = mapper.Map<List<GoodDTO>>(query);
            res.PageData = result.OrderByDescending(x => x.Id).Skip((request.pageindex - 1) * request.pagesize).Take(request.pagesize).ToList();
            return Task.FromResult(res);
        }
    }
}
